package com.lwl.mini.util;

import com.lwl.mini.builder.BuilderException;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author lwl
 * @create 2022/4/12 10:49
 */
public class LoadingUtils {
    private static final LoadingUtils INSTANCE = new LoadingUtils();

    public static LoadingUtils getInstance() {
        return INSTANCE;
    }

    private LoadingUtils() {

    }

    /**
     * 将package中的所有类读取出来
     * @param packagePath
     * @return
     */
    public List<String> list(String packagePath) {
        try {
            List<String> name = new ArrayList<>();
            for(URL url:getResources(packagePath)){
                name.addAll(list(url,packagePath));
            }
            return name;
        } catch (Exception e) {
            throw new BuilderException("The Error Cause:" + e, e);
        }
    }

    /**
     * 读取包下的文件路径
     * @param url 包的url路径
     */
    public List<String> list(URL url,String path) throws IOException {
        InputStream is = url.openStream();
        List<String> resources = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            List<String> lines = new ArrayList<>();
            for(String line;(line = reader.readLine())!=null;){
                lines.add(line);
                if(getResources(path + '/' +line).isEmpty()){
                    lines.clear();
                    break;
                }
            }
            for (String line:lines){
                resources.add(path +'/'+ line);
            }
            return resources;
        }catch (FileNotFoundException e){
            throw new BuilderException("加载Mapper出现异常，请检查配置文件中package标签的路径 \n"+e,e);
        }finally {
            if(is!=null){
                is.close();
            }
        }


    }


    public List<URL> getResources(String packagePath) throws IOException {
       return Collections.list(Thread.currentThread().getContextClassLoader().getResources(packagePath));
    }

    public Class classLoad(String classPath) throws ClassNotFoundException {
        return Thread.currentThread().getContextClassLoader().loadClass(classPath);
    }

}
